Page({
  data: {
    autoConnect: true,
    notifications: true,
    dataSync: true,
    deviceInfo: {
      connected: false,
      name: '',
      battery: null,
      signal: null,
      firmware: null
    }
  },

  onLoad() {
    this.loadSettings()
    this.loadDeviceInfo()
  },

  onShow() {
    this.loadDeviceInfo()
  },

  // 加载设置
  loadSettings() {
    try {
      const settings = wx.getStorageSync('appSettings') || {}
      this.setData({
        autoConnect: settings.autoConnect !== undefined ? settings.autoConnect : true,
        notifications: settings.notifications !== undefined ? settings.notifications : true,
        dataSync: settings.dataSync !== undefined ? settings.dataSync : true
      })
    } catch (error) {
      console.error('加载设置失败:', error)
    }
  },

  // 加载设备信息
  loadDeviceInfo() {
    try {
      // 修正：使用正确的存储键名
      const connectedDeviceInfo = wx.getStorageSync('connectedDeviceInfo')
      const lastConnectedDevice = wx.getStorageSync('lastConnectedDevice')
      
      if (connectedDeviceInfo && lastConnectedDevice) {
        this.setData({
          deviceInfo: {
            ...this.data.deviceInfo,
            ...connectedDeviceInfo,
            connected: true
          }
        })
      } else {
        this.setData({
          deviceInfo: {
            ...this.data.deviceInfo,
            connected: false
          }
        })
      }
    } catch (error) {
      console.error('加载设备信息失败:', error)
    }
  },

  // 导航到具体设置页面
  navigateToSetting(e) {
    const type = e.currentTarget.dataset.type
    
    switch (type) {
      case 'anc':
        wx.navigateTo({
          url: '/pages/anc/anc'
        })
        break
      case 'audio':
        wx.navigateTo({
          url: '/pages/audio/audio'
        })
        break
      case 'audiocuration':
        wx.navigateTo({
          url: '/pages/audiocuration/audiocuration'
        })
        break
      case 'voice':
        wx.navigateTo({
          url: '/pages/voice/voice'
        })
        break
      case 'gestures':
        wx.navigateTo({
          url: '/pages/gestures/gestures'
        })
        break
      case 'earbudfit':
        wx.navigateTo({
          url: '/pages/earbudfit/earbudfit'
        })
        break
      case 'handset':
        wx.navigateTo({
          url: '/pages/handset/handset'
        })
        break
      case 'upgrade':
        wx.navigateTo({
          url: '/pages/upgrade/upgrade'
        })
        break
      case 'logs':
        wx.navigateTo({
          url: '/pages/logs/logs'
        })
        break
      case 'statistics':
        wx.navigateTo({
          url: '/pages/statistics/statistics'
        })
        break
      case 'feedback':
        wx.navigateTo({
          url: '/pages/feedback/feedback'
        })
        break
      case 'about':
        this.showAboutInfo()
        break
      default:
        wx.showToast({
          title: '功能开发中',
          icon: 'none'
        })
    }
  },

  // 显示关于信息
  showAboutInfo() {
    wx.showModal({
      title: '关于 Gaia Client',
      content: '版本: 1.0.0\n\nQualcomm 蓝牙设备管理客户端\n\n© 2020-2023 Qualcomm Technologies, Inc.',
      showCancel: false,
      confirmText: '确定'
    })
  },

  // 切换自动连接
  toggleAutoConnect(e) {
    const value = e.detail.value
    this.setData({
      autoConnect: value
    })
    this.saveSettings()
  },

  // 切换通知提醒
  toggleNotifications(e) {
    const value = e.detail.value
    this.setData({
      notifications: value
    })
    this.saveSettings()
  },

  // 切换数据同步
  toggleDataSync(e) {
    const value = e.detail.value
    this.setData({
      dataSync: value
    })
    this.saveSettings()
  },

  // 保存设置
  saveSettings() {
    try {
      const settings = {
        autoConnect: this.data.autoConnect,
        notifications: this.data.notifications,
        dataSync: this.data.dataSync
      }
      wx.setStorageSync('appSettings', settings)
    } catch (error) {
      console.error('保存设置失败:', error)
    }
  },

  // 断开设备连接
  async disconnectDevice() {
    wx.showModal({
      title: '确认断开',
      content: '确定要断开当前设备连接吗？',
      success: async (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '断开连接中...'
          })
          
          try {
            // 导入蓝牙和GAIA管理器
            const bluetoothModule = require('../../utils/bluetooth.js')
            const bluetoothManager = bluetoothModule.bluetoothManager
            const gaiaModule = require('../../utils/gaiaManager.js')
            const gaiaManager = gaiaModule.gaiaManager
            
            // 1. 先断开GAIA连接
            try {
              gaiaManager.disconnect()
              console.log('GAIA连接已断开')
            } catch (error) {
              console.warn('断开GAIA连接时出错:', error)
            }
            
            // 2. 断开蓝牙连接
            try {
              await bluetoothManager.disconnect()
              console.log('蓝牙连接已断开')
            } catch (error) {
              console.warn('断开蓝牙连接时出错:', error)
            }
            
            // 3. 等待断开操作完成
            await new Promise(resolve => setTimeout(resolve, 500))
            
            // 4. 清理本地存储
            wx.removeStorageSync('connectedDeviceInfo')
            wx.removeStorageSync('lastConnectedDevice')
            
            // 4. 更新页面状态
            this.setData({
              deviceInfo: {
                ...this.data.deviceInfo,
                connected: false
              }
            })
            
            wx.hideLoading()
            wx.showToast({
              title: '已断开连接',
              icon: 'success'
            })
            
            // 5. 跳转到设备发现页面
            setTimeout(() => {
              wx.redirectTo({
                url: '/pages/discovery/discovery'
              })
            }, 1000) // 延迟1秒跳转，让用户看到断开成功的提示
            
          } catch (error) {
            wx.hideLoading()
            console.error('断开连接失败:', error)
            wx.showToast({
              title: '断开连接失败',
              icon: 'error'
            })
          }
        }
      }
    })
  }
})


